package service

import (
	"errors"
	"server/client/casbin"
	"server/model/request"
)

func UpdateCasbin(roleId string, casbinInfo []request.CasbinInfo) error {

	e := casbin.CasbinClient

	//清除当前role对应的规则，不然会冲突

	for _, info := range casbinInfo {
		success, _ := e.RemoveFilteredPolicy(0, roleId, info.Path)
		if success == false {
			return errors.New("清除规则失败")
		}
	}

	//更新最新的role规则。
	var rules [][]string

	for _, v := range casbinInfo {
		rules = append(rules, []string{roleId, v.Path, v.Method})
	}

	ok, _ := e.AddPolicies(rules)

	if ok == false {
		return errors.New("存在相同api,添加失败,请联系管理员")
	}
	return nil
}

func GetPolicyPathByRoleId(roleID string) (pathMaps []request.CasbinInfo) {
	e := casbin.CasbinClient

	list := e.GetFilteredPolicy(0, roleID)
	for _, v := range list {
		pathMaps = append(pathMaps, request.CasbinInfo{
			Path:   v[1],
			Method: v[2],
		})
	}
	return pathMaps
}

func ClearCasbin(v int, p ...string) bool {
	e := casbin.CasbinClient

	success, _ := e.RemoveFilteredPolicy(v, p...)
	return success
}
